package com.jp.refreshlocalcacheclient.process;

import com.jp.refreshlocalcacheclient.data.CacheMethod;
import com.jp.refreshlocalcacheclient.net.netty.response.RegisterResponseMsg;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jipeng
 * @Description: 处理刷新的流程
 * @Date: Created in 2020/4/29 15:46
 */
@Component
public class HandleRefreshProcess {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 保存缓存key和方法的关系
     */
    private Map<String, CacheMethod> cacheMethodMap = new HashMap<>();

    /**
     * 添加缓存方法
     * @param cacheMethod
     */
    public void addCacheMethod(CacheMethod cacheMethod){
        cacheMethodMap.put(cacheMethod.getKey(),cacheMethod);
    }

    /**
     * 根据 缓存key 查找缓存方法
     * @param key
     * @return
     */
    public CacheMethod getCacheMethod(String key){
        return cacheMethodMap.get(key);
    }

    /**
     * 处理刷新方法的执行
     * @param cacheKey
     */
    public boolean handleRefresh(String cacheKey){
        CacheMethod cacheMethod = getCacheMethod(cacheKey);

        if(cacheMethod == null){
            //目前提示到控制台
            logger.error("key {} did not find the method", cacheKey);
            return false;
        }

        ReflectionUtils.invokeMethod(cacheMethod.getMethod(),cacheMethod.getBeanObj());

        //目前提示到控制台
        logger.info("key {} executes method {} of class {}  success", cacheKey, cacheMethod.getMethod().getName(), cacheMethod.getBeanObj().getClass().getName());
        return true;
    }

    /**
     * 在远程服务端注册缓存key
     * @param ctx
     */
    public void registerCacheKey(ChannelHandlerContext ctx){
        for (String key : cacheMethodMap.keySet()){
            new RegisterResponseMsg(key).sendTo(ctx);
        }
    }
}
